﻿using LuShanTea.DTO;
using LuShanTea.IService;
using LuShanTea.Service.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LuShanTea.Service
{
    class GoodService : IGoodService
    {
        // 添加商品
        public long AddNew(GoodDTO good)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                Good g = new Good();
                BaseService<Pack> bs = new BaseService<Pack>(ctx);
                // 获取用户传入的包装类型
                var Goodpacks = bs.GetAll().Where(p => good.PackIds.Contains(p.Id));
                // 遍历循环，将所有的包装类型添加到包装表中
                foreach (var pack in Goodpacks)
                {
                    g.Packs.Add(pack);
                }
                BaseService<Good> bs2 = new BaseService<Good>(ctx);
                //根据商品名字判断要添加的商品是否已经
                bool exist = bs2.GetAll().Any(d => d.Name == good.Name);
                if (exist)
                {
                    throw new ArgumentException($"商品名为{good.Name}的商品已经存在");
                }

                g.CateGoriesId = good.CateGoriesId;
                g.CityId = good.CityId;
                g.Describe = good.Descible;
                g.Name = good.Name;
                g.Pre_Price = good.PrePrice;
                g.Price = good.Price;
                g.Selled = good.Selled;
                g.TotalCount = good.TotalCount;
                g.Weight = good.Weight;

                ctx.Goods.Add(g);
                ctx.SaveChanges();
                return g.Id;
            }
        }

        // 获取所有的商品
        public GoodDTO[] GetAll()
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);
                return bs.GetAll().Include(g => g.Category).Include(g => g.Packs).AsNoTracking().ToList().Select(g => ToDTO(g)).ToArray();
            }
        }

        // 根据商品id获取商品
        public GoodDTO GetByGoodId(long goodId)
        {

            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);
                var data = bs.GetById(goodId);
                if (data == null)
                {
                    //throw new ArgumentException($"商品id为：{goodId}的商品不存在");
                    return null;
                }

                return ToDTO(data);
            }
        }

        // 获取该数组下所有的商品
        public GoodDTO[] GetByGoodIds(long[] goodIds)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);
                List<GoodDTO> listGoods = new List<GoodDTO>();
                foreach (var goodId in goodIds)
                {

                    var good = bs.GetById(goodId);
                    ToDTO(good);
                }
                return listGoods.ToArray();
            }
        }

        //// 获取该类型下所有的商品
        public GoodDTO[] GetGoodsByCategId(long categId)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);
                var data = bs.GetAll().Where(g => g.CateGoriesId == categId);
                if (data == null)
                {
                    throw new ArgumentException($"无categId为{categId}类型的商品");
                }

                return data.Include(g => g.City).Include(g => g.Packs).AsNoTracking().ToList().Select(g => ToDTO(g)).ToArray();
            }
        }
        //  获取该类型下最新的n件商品
        // 注意：文档的方法中忘记添加categId这个参数
        public GoodDTO[] GetGoodsByNewCategId(long categId, int num)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);

                return bs.GetAll().OrderByDescending(e => e.CreateDateTime).Take(num).Include(g => g.Packs).AsNoTracking().ToList().Where(g => g.CateGoriesId == categId).Select(g => ToDTO(g)).ToArray();
            }
        }

        // 获取最新添加的n件商品
        public GoodDTO[] GetNewGoods(int num)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);

                return bs.GetAll().OrderByDescending(e => e.Selled).Take(num).Include(g => g.Packs).AsNoTracking().ToList().Select(g => ToDTO(g)).ToArray();
            }
        }

        // 获取销售量最好的几件商品
        public GoodDTO[] GetSelledTop(int num)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);

                return bs.GetAll().OrderByDescending(e => e.CreateDateTime).Take(num).Include(g => g.Packs).AsNoTracking().ToList().Select(g => ToDTO(g)).ToArray();
            }
        }

        public void MakeDelete(long goodId)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);
                bs.MakeDelete(goodId);
            }
        }

        // 待定：根据不同的条件，筛选出不同的数据
        public GoodDTO[] SearchGoodsPageData()
        {
            throw new NotImplementedException();
        }


        public void UpdataGoodSelled(long goodId, long selled)
        {

            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);

                var good = bs.GetAll().SingleOrDefault(g => g.Id == goodId);

                if (good == null)
                {
                    throw new ArgumentNullException("商品Id为:" + goodId + "不存在");
                }

                good.Selled += selled;

                ctx.SaveChanges();
            }
        }
        public void Updata(GoodDTO good)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);
                BaseService<Pack> bs2 = new BaseService<Pack>(ctx);
                var g = bs.GetById(good.Id);
                if (g == null)
                {
                    throw new ArgumentException($"商品名为{good.Name}的商品不存在");
                }

                g.Packs.Clear(); // 清除该商品所有包装类型
                // 获取该商品的所有包装类型
                var goodPacks = bs2.GetAll().Where(p => good.PackIds.Contains(p.Id));
                foreach (var pack in goodPacks)
                {
                    g.Packs.Add(pack);
                }
                g.CateGoriesId = good.CateGoriesId;
                g.CityId = good.CityId;
                g.Describe = good.Descible;
                // g.GoodAttrsId = good.GoodAttrsId;
                g.Id = good.Id;
                g.Name = good.Name;
                g.Pre_Price = good.PrePrice;
                g.Price = good.Price;
                g.Selled = good.Selled;
                g.TotalCount = good.TotalCount;
                g.Weight = good.Weight;

                ctx.SaveChanges();
            }
        }
        public GoodDTO ToDTO(Good g)
        {
            GoodDTO dto = new GoodDTO();
            dto.CityName = g.City.Name;
            dto.CatoryName = g.Category.Name;
            dto.CateGoriesId = g.CateGoriesId;
            dto.CityId = g.CityId;
            dto.CreateDateTime = g.CreateDateTime;
            dto.Descible = g.Describe;
            dto.Id = g.Id;
            dto.Name = g.Name;
            dto.PackIds = g.Packs.Select(e => e.Id).ToArray();
            dto.PrePrice = g.Pre_Price;
            dto.Price = g.Price;
            dto.Selled = g.Selled;
            dto.TotalCount = g.TotalCount;
            dto.Weight = g.Weight;
            return dto;
        }
        // 分页获取商品
        public GoodDTO[] GetPageData(int index)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);
                return bs.GetPageData(index, 10).Include(g => g.Category).Include(g => g.Packs).AsNoTracking().ToList().Select(g => ToDTO(g)).ToArray();
            }
        }
        // 分页获取指定类型下的商品
        public GoodDTO[] GetPageDataGoodsByCategId(long categId, int index, string orderBy, string priceRange, long PackId, string keyword)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);

                var data = bs.GetAll().Where(g => g.CateGoriesId == categId);
                if (data == null)
                {
                    throw new ArgumentException($"无categId为{categId}类型的商品");
                }

                // 将价格区间截取开来，获取价格区间
                string[] pRange = priceRange.Split('-');
                int startPrice = Convert.ToInt32(pRange[0]);
                int endPrice = Convert.ToInt32(pRange[1]);

                // 1000以上的
                if (endPrice == 0 && startPrice != 0)
                {
                    data = data.Where(e => (e.Price > startPrice));
                }
                // 0-1000之间的
                else if (endPrice != 0)
                {
                    data = data.Where(e => (e.Price > startPrice) && (e.Price < endPrice));
                }
                // 如果是 0-0则表示获取所有价格区间的商品
                if (PackId != 0)
                {
                    data = data.Where(e => e.Packs.Any(a => a.Id == PackId));
                }

                // 根据传入不同排序规则赛选出不同数据
                switch (orderBy)
                {
                    case "all":
                        data = data.OrderBy(e => e.CreateDateTime).OrderByDescending(e => e.Selled).OrderByDescending(e => e.Price);
                        break;
                    case "sale":
                        data = data.OrderByDescending(e => e.Selled);
                        break;
                    case "price":
                        data = data.OrderByDescending(e => e.Price);
                        break;
                    case "new":
                        data = data.OrderBy(e => e.CreateDateTime);
                        break;
                    default:
                        data = data.OrderBy(e => e.CreateDateTime);
                        break;
                }
                data = data.Skip((index - 1) * 5).Take(5);
                return data.ToList().Select(e => ToDTO(e)).ToArray();


            }
        }

        public GoodDTO[] GetTakeGoodsByCategId(long categId)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);
                var data = bs.GetAll().Where(g => g.CateGoriesId == categId);
                if (data == null)
                {
                    throw new ArgumentException($"无categId为{categId}类型的商品");
                }

                return data.Take(8).Include(g => g.City).Include(g => g.Packs).AsNoTracking().ToList().Select(g => ToDTO(g)).ToArray();
            }
        }
        // 获取销售最好的前5件商品
        public GoodDTO[] GetSelledTakeAll()
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);
                return bs.GetAll().Include(g => g.Category).Include(g => g.Packs).AsNoTracking().OrderByDescending(e => e.Selled).Take(5).ToList().Select(g => ToDTO(g)).ToArray();
            }
        }
        // 获取最新上线的5条商品
        public GoodDTO[] GetNewTakeAll()
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);
                return bs.GetAll().Include(g => g.Category).Include(g => g.Packs).AsNoTracking().OrderBy(e => e.CreateDateTime).Take(5).ToList().Select(g => ToDTO(g)).ToArray();
            }
        }

        public long GetDayGoodCount()
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);
                DateTime time = DateTime.Now.AddHours(-24);
                return bs.GetAll().LongCount(e => e.CreateDateTime> time);
            }
        }
    }
}
